#include "soundbase.h"
#include <QEventLoop>

SoundBase::SoundBase(QObject *parent) : QObject(parent)
{
    API_id = "25363030";
    API_key = "U3G8WYn6XyCo8oWUvG3SuWQA";
    API_access_token="";
    API_language="zh";
    API_secret_key = "Yjo6Qcau6r2V7kMwLmgYimAG9SIoAVRo";
    API_record_path="C:/Users/Administrator/Desktop/UBTV4.m4a";

    m_manager = new QNetworkAccessManager(this);
    //connect(m_manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinish(QNetworkReply*)));
}

QString SoundBase::getAccessTokenUrl(QString apiId, QString secretKey)
{
    QString url = QString("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2")
            .arg(apiId).arg(secretKey);
    return url;
}

QString SoundBase::getHead()
{
    QString head = "application/x-www-form-urlencoded";
    return head;
}

QString SoundBase::getAccessToken(QString apiId, QString secretKey)
{
    QString url = getAccessTokenUrl(apiId,secretKey);
    qDebug()<<url;
    QNetworkRequest quest;
    quest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    quest.setUrl(QUrl(url));
#if 0
    m_manager->get(quest);
#else
    QNetworkReply *reply = m_manager->get(quest);

    QEventLoop loopEv;
    connect(m_manager,&QNetworkAccessManager::finished,&loopEv,&QEventLoop::quit);
    loopEv.exec();
    QString strJsonAccess=reply->readAll();//得到http返回的API_access_token口令
    API_access_token = paraseAccessToken(strJsonAccess);
    reply->deleteLater();
    return API_access_token;
#endif
}

QString SoundBase::paraseAccessToken(QString jsonString)
{
    QString ret = "";

    if(jsonString==NULL)
    {
        qWarning("错误！没有得到Json包");
    }
    //对百度语音返回信息(JSON包)进行解析
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(jsonString.toLocal8Bit().data(), &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
       qWarning() << "BaiDu json error!";
       return ret;
    }
    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("access_token"))
    {
        ret = rootObj.value("access_token").toString();
    }
    if(ret=="")
    {
        qWarning("access_token口令获取失败！");
        return ret;
    }
    else
    {
        qDebug() << "get access_token successed:"<<ret;
    }
    return ret;
}

void SoundBase::replyFinish(QNetworkReply * reply)
{
     //解析JSON
     QByteArray allData = reply->readAll();
}

QByteArray SoundBase::post(QNetworkRequest request, QByteArray btArray)
{
    QByteArray ret;
    QNetworkReply *reply = m_manager->post(request,btArray);
    QEventLoop loopEv;
    connect(m_manager,&QNetworkAccessManager::finished,&loopEv,&QEventLoop::quit);
    loopEv.exec();
    ret = reply->readAll();
    reply->deleteLater();
    return ret;
}
